import { createRouter, createWebHistory } from 'vue-router'

// 路由懒加载
const Layout = () => import('@/views/Home.vue')

// 公共路由
const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', hidden: true }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard/workspace',
    children: [
      {
        path: '/dashboard/workspace',
        name: 'Workspace',
        component: () => import('@/views/dashboard/workspace.vue'),
        meta: { title: '工作台', icon: 'el-icon-monitor' }
      },
      {
        path: '/system/user',
        name: 'User',
        component: () => import('@/views/system/user/index.vue'),
        meta: { title: '用户管理', icon: 'el-icon-user' }
      }
    ]
  },
  // 匹配所有路径 - 放在最后
  { 
    path: '/:pathMatch(.*)*', 
    redirect: '/404', 
    meta: { hidden: true } 
  }
]

// 创建路由
const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes,
  // 平滑滚动
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - Vue3管理系统` : 'Vue3管理系统'
  
  // 获取token
  const token = localStorage.getItem('token')
  
  // 如果有token
  if (token) {
    // 如果是登录页，重定向到首页
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    // 如果没有token，并且不是登录页，重定向到登录页
    if (to.path !== '/login') {
      next({ path: '/login' })
    } else {
      next()
    }
  }
})

export default router 